package com.medical.standard.controller.export;

import com.medical.standard.service.ExportService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/export/document")
public class DocumentExportServlet extends HttpServlet {

    private ExportService exportService;

    @Override
    public void init() throws ServletException {
        this.exportService = new ExportService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        try {
            // 读取JSON请求体
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            String jsonString = sb.toString();

            // 使用简单的JSON解析（手动解析）
            Map<String, Object> requirementData = parseJsonManually(jsonString);

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            String fileName = new String("产品技术要求.docx".getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 导出Word文档
            exportService.exportProductRequirement(response, requirementData);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"error\": \"导出失败: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 手动解析简单JSON
     */
    private Map<String, Object> parseJsonManually(String jsonString) {
        Map<String, Object> result = new HashMap<>();

        // 移除首尾的大括号
        String content = jsonString.trim();
        if (content.startsWith("{") && content.endsWith("}")) {
            content = content.substring(1, content.length() - 1).trim();
        }

        // 按逗号分割键值对
        String[] pairs = content.split(",");
        for (String pair : pairs) {
            String[] keyValue = pair.split(":", 2);
            if (keyValue.length == 2) {
                String key = extractString(keyValue[0].trim());
                String value = extractString(keyValue[1].trim());
                result.put(key, value);
            }
        }

        return result;
    }

    /**
     * 从JSON字符串中提取实际字符串值
     */
    private String extractString(String jsonValue) {
        if (jsonValue.startsWith("\"") && jsonValue.endsWith("\"")) {
            return jsonValue.substring(1, jsonValue.length() - 1);
        }
        return jsonValue;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 返回产品技术要求模板
        response.setContentType("application/json;charset=UTF-8");
        String template = "{" +
                "\"template\": \"医疗器械产品技术要求模板\"," +
                "\"sections\": [\"产品型号/规格及其划分说明\", \"性能指标\", \"检验方法\", \"术语\"]" +
                "}";
        response.getWriter().write(template);
    }
}